package com.xquant.trade.account.service;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.xquant.common.core.constant.DictConstant;
import com.xquant.common.core.constant.PermConstant;
import com.xquant.common.core.utils.StringUtils;
import com.xquant.common.security.utils.SecurityUtils;
import com.xquant.trade.account.entity.Account;
import com.xquant.trade.account.mapper.AccountMapper;
import com.xquant.trade.risk.service.GroupService;
import com.xquant.system.api.RemotePermService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service("AccountService")
@Component
public class AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private GroupService groupService;


    @Autowired
    private RemotePermService permService;
    public List<Account> querySelfAccountByPage(Map map) {
        List<Account> list =new ArrayList<>();
        //如果不控制权限
        if("false".equals(MapUtil.getStr(map,"isAuth"))){
            list=accountMapper.querySelfAccountNoPermByPage(map);
        }else{
            String accFlag=permService.getPermFlag( PermConstant.AUTH_TYPE.ACCOUNT);
            //如果是全部权限，读取部门
            if(StrUtil.isNotEmpty(accFlag)&& DictConstant.YES_NO.YES.equals(accFlag)){
                list=accountMapper.querySelfAccountDeptPermByPage(map);
            }else{
                //如果是个人权限
                list=accountMapper.querySelfAccountUserPermByPage(map);
            }
        }
        return list;
    }

    public PageInfo<Account> querySelfAccountCombox(Map<String, Object> param) {
        List<Account> list =new ArrayList<>();
        //如果不控制权限
        if("false".equals(MapUtil.getStr(param,"isAuth"))){
            list=accountMapper.querySelfAccountNoPermByPage(param);
        }else{
            String accFlag=permService.getPermFlag( PermConstant.AUTH_TYPE.ACCOUNT);
            //如果是全部权限，读取部门
            if(StrUtil.isNotEmpty(accFlag)&& DictConstant.YES_NO.YES.equals(accFlag)){
                list=accountMapper.querySelfAccountDeptPermByPage(param);
            }else{
                //如果是个人权限
                list=accountMapper.querySelfAccountUserPermByPage(param);
            }
        }
        return new PageInfo<Account>(list);
    }


    public PageInfo<Account> queryPartyAccountByPage(Map map) {
        return new PageInfo(accountMapper.queryPartyAccountByPage(map));
    }

    public void addAccount(Account account) {
        List<Account> accUserList=new ArrayList<>();
        List<Account>  accDeptList=new ArrayList<>();
        //创建人所属部门
        String createDept=SecurityUtils.getLoginUser().getSysUser().getDeptId().toString();
        //创建人上级部门
        String upDept=null;
        Map<String,String> paramMap=new HashMap<>();
        paramMap.put("deptId",createDept);
        Map<String,String> resultMap=accountMapper.getDept(paramMap);
        if(resultMap!=null&& StringUtils.isNotNull(resultMap.get("ancestors").toString())){
            upDept=resultMap.get("ancestors").toString().substring(1);
        }
        if(StringUtils.isNotNull(upDept)){
            upDept+=","+createDept;
        }else{
            upDept=createDept;
        }
        String[] dArray=upDept.split(",");
        for (String did: dArray) {
            if(StringUtils.isNotNull(did)&&!"".equals(did)){
                account.setAccRightUser(account.getAccRightUser()+",d:" +did);
            }
        }

        String[] rightArray=account.getAccRightUser().split(",");
        rightArray=ArrayUtil.distinct(rightArray);
        accountMapper.addAccount(account);
        HashMap map= com.alibaba.fastjson2.JSONObject.parseObject(account.getAccRight(),HashMap.class);
        int accId= account.getAccId();
        for (String authId:rightArray) {
            Account act=new Account();
            if("u".equals(authId.split(":")[0])){
                act.setAccId(accId);
                act.setUserId(authId.split(":")[1]);
                act.setAccRight(map.get(act.getUserId()).toString());
                 if(authId.split(":")[1].equals(account.getCreater())){
                     act.setAccRight("2");//创建人必须读写权限
                 }
                accUserList.add(act);
            }else if("d".equals(authId.split(":")[0])){
                act.setAccId(accId);
                act.setUserId(authId.split(":")[1]);
                //部门统一为写权限，界面放开选择后需要调整
                act.setAccRight("2");
                if(StringUtils.isNotNull(upDept)){
                    String[] upDeptArray=upDept.split(",");
                    for (String did:upDeptArray) {
                        if(authId.split(":")[1].equals(did)){
                            act.setAccRight("2");//创建人所属部门及上级部门必须读写权限
                        }
                    }
                }
                accDeptList.add(act);
            }
        }

        if(accUserList.size()>0){
            //增加tsys_user_perm数据
            accountMapper.batchUpdateUserPerm(accUserList,String.valueOf(accId));
            //增加tacc_user数据
            accountMapper.batchInsertAccUser(accUserList);
        }
        if(accDeptList.size()>0){
            //增加tsys_dept_perm数据
            accountMapper.batchUpdateDeptPerm(accDeptList,String.valueOf(accId));
            //增加tacc_dept 数据
            accountMapper.batchInsertAccDept(accDeptList);
        }
    }

    public void updateAccount(Account account) {
        accountMapper.updateAccount(account);
    }

    public void deleteAccount(Account account) {
        if (ObjectUtil.isNotNull(account)){
            if (ObjectUtil.isNotNull(account.getAccId())){
                accountMapper.deleteAccount(account);
                //删除用户、部门权限表
                Map<String,Object> param = new HashMap<>();
                param.put("accId",String.valueOf(account.getAccId()));
                accountMapper.removeUserPermAccount(param);
                accountMapper.removeDeptPermAccount(param);
                //删除账户读写权限表
                accountMapper.deleteAccUser(account);
                accountMapper.deleteAccDept(account);
            }
        }

    }

    public List<Map> queryAccountUser(Map map) {
        return accountMapper.queryAccountUser(map);
    }

    public List<Map> queryAccountDept(Map map){
        return accountMapper.queryAccountDept(map);
    }

    public void saveAccountUser(Map map) {
        accountMapper.saveAccountUser(map);
    }
    public void saveAccountDept(Map map) {
        accountMapper.saveAccountDept(map);
    }


    @Transactional
    public void updateAccountUser(Map params) {

        List<Integer> userIds = (List<Integer>) params.get("userIds");
        String accRight = (String) params.get("accRight");
        String deptId = String.valueOf(params.get("deptId"));

        //存放上级部门
        ArrayList<String> deptAncestors = new ArrayList<>();
        //将创建人所属部门的上级部门加入deptPerms
        String deptAncestorIds = groupService.getDeptAncestors(deptId);
        List<String> deptAncestorIdArrs = Arrays.asList(deptAncestorIds.split(","));
        for (String deptAncestorArr : deptAncestorIdArrs) {
            if ("0".equals(deptAncestorArr) != true) {
                deptAncestors.add(deptAncestorArr);
            }
        }

        //读写表修改和权限表删除
        for(Integer userId : userIds){
            Map<String,Object> param = new HashMap<>();
            param.put("userId",userId);
            param.put("accId",params.get("accId"));
            param.put("deptId",deptId);
            param.put("accRight", accRight);
            if("1".equals(queryAccFlagByUserId(String.valueOf(userId)))){
                //accFlag是1,改部门权限
                List<Map> list = queryAccountDept(param);
                if (list.size() == 0 && !"0".equals(accRight)) {
                    //读写表无数据则插入
                    saveAccountDept(param);
                } else if(list.size() != 0 && !"0".equals(accRight)){
                    updateAccountDept(param);
                }else if(list.size() != 0 && "0".equals(accRight)){
                    deleteAccountDept(param);
                }
                //删除权限表相关deptId
                removeDeptPermAccount(param);
                if(!"0".equals(accRight)) {
                    params.put("deptIds",Arrays.asList(deptId));
                    accountMapper.updateDeptPermAccount(params);
                    Map<String,Object> deptParams = new HashMap<>();
                    deptParams.put("deptIds",deptAncestors);
                    deptParams.put("accId",params.get("accId"));
                    deptParams.put("accRight",2);
                    for(String deId : deptAncestors){
                        deptParams.put("deptId",deId);
                        accountMapper.deleteAccountDept(deptParams);
                        accountMapper.saveAccountDept(deptParams);
                        removeDeptPermAccount(deptParams);
                    }
                    if(deptAncestors.size()>0){
                        accountMapper.updateDeptPermAccount(deptParams);
                    }

                }

            }else{
                List<Map> list = queryAccountUser(param);
                if (list.size() == 0 && !"0".equals(accRight)) {
                    //读写表无数据则插入
                    saveAccountUser(param);
                } else if(list.size() != 0 && !"0".equals(accRight)){
                    accountMapper.updateAccountUser(param);
                }else if(list.size() != 0 && "0".equals(accRight)){
                    deleteAccountUser(param);
                }
                //删除权限表相关userId
                removeUserPermAccount(param);
            }

        }
        if(!"0".equals(accRight)) {
            updateAccountUserPerm(params);
        }
    }

    public void updateAccountDept(Map map) {
        accountMapper.updateAccountDept(map);
    }

    public void updateConfigUserAuthor(Map params) {
        accountMapper.updateConfigUserAuthor(params);
    }


    public List<Map> queryPartyAccout(Map params) {
        List<Map> list = accountMapper.queryPartyAccout(params);
        return list;
    }

    public void deleteAccountUser(Map map) {
        accountMapper.deleteAccountUser(map);
    }

    public void deleteAccountDept(Map map) {
        accountMapper.deleteAccountDept(map);
    }

    public boolean checkAccName(Account account) {
        Account getByName = accountMapper.checkAccName(account.getAccName());
        if (getByName==null){
            return true;
        }else {
            if (getByName.getAccId().equals(account.getAccId())){
                return true;
            }else {
                return false;
            }
        }
    }
    public boolean checkAccCode(Account account) {
        Account getByCode = accountMapper.checkAccCode(account.getAccCode());
        if (getByCode==null){
            return true;
        }else {
            if (getByCode.getAccId().equals(account.getAccId())){
                return true;
            }else {
                return false;
            }
        }
    }

    public List getAccountUserAndDeptPerm(Map<String, Object> param) {
        List<String> userPermUserId = accountMapper.getUserPermUserId(param);
        List<String> deptPermDeptId = accountMapper.getDeptPermDeptId(param);
        userPermUserId.addAll(deptPermDeptId);
        return userPermUserId;
    }


    public void updateAccountPerm(Account account) {
        Map<String,Object> param = new HashMap();
        param.put("accId",String.valueOf(account.getAccId()));
        accountMapper.removeDeptPermAccount(param);
        accountMapper.removeUserPermAccount(param);
        accountMapper.deleteAccUser(account);
        accountMapper.deleteAccDept(account);

        List<Account> accUserList=new ArrayList<>();
        List<Account>  accDeptList=new ArrayList<>();
        //创建人所属部门
        String createDept=SecurityUtils.getLoginUser().getSysUser().getDeptId().toString();
        //创建人上级部门
        String upDept=null;
        Map<String,String> paramMap=new HashMap<>();
        paramMap.put("deptId",createDept);
        Map<String,String> resultMap=accountMapper.getDept(paramMap);
        if(resultMap!=null&& StringUtils.isNotNull(resultMap.get("ancestors").toString())){
            upDept=resultMap.get("ancestors").toString().substring(1);
        }
        if(StringUtils.isNotNull(upDept)){
            upDept+=","+createDept;
        }else{
            upDept=createDept;
        }
        String[] dArray=upDept.split(",");
        for (String did: dArray) {
            if(StringUtils.isNotNull(did)&&!"".equals(did)){
                account.setAccRightUser(account.getAccRightUser()+",d:" +did);
            }
        }

        String[] rightArray=account.getAccRightUser().split(",");
        rightArray=ArrayUtil.distinct(rightArray);
        HashMap map= com.alibaba.fastjson2.JSONObject.parseObject(account.getAccRight(),HashMap.class);
        int accId= account.getAccId();
        for (String authId:rightArray) {
            Account act=new Account();
            if("u".equals(authId.split(":")[0])){
                act.setAccId(accId);
                act.setUserId(authId.split(":")[1]);
                act.setAccRight(map.get(act.getUserId()).toString());
                if(authId.split(":")[1].equals(account.getCreater())){
                    act.setAccRight("2");//创建人必须读写权限
                }
                accUserList.add(act);
            }else if("d".equals(authId.split(":")[0])){
                act.setAccId(accId);
                act.setUserId(authId.split(":")[1]);
                act.setAccRight("2");
                if(StringUtils.isNotNull(upDept)){
                    String[] upDeptArray=upDept.split(",");
                    for (String did:upDeptArray) {
                        if(authId.split(":")[1].equals(did)){
                            act.setAccRight("2");//创建人所属部门及上级部门必须读写权限
                        }
                    }
                }
                accDeptList.add(act);
            }
        }

        if(accUserList.size()>0){
            //增加tsys_user_perm数据
            accountMapper.batchUpdateUserPerm(accUserList,String.valueOf(accId));
            //增加tacc_user数据
            accountMapper.batchInsertAccUser(accUserList);
        }
        if(accDeptList.size()>0){
            //增加tsys_dept_perm数据
            accountMapper.batchUpdateDeptPerm(accDeptList,String.valueOf(accId));
            //增加tacc_dept 数据
            accountMapper.batchInsertAccDept(accDeptList);
        }
    }


    public void removeUserPermAccount(Map param){
        param.put("accId",String.valueOf(param.get("accId")));
        accountMapper.removeUserPermAccountByUserId(param);
    }
    public void removeDeptPermAccount(Map param){
        param.put("accId",String.valueOf(param.get("accId")));
        accountMapper.removeDeptPermAccountByDeptId(param);
    }


    public void updateAccountUserPerm(Map param){
        List<Account> accountList = new ArrayList<>();
        List<Integer> userIds = (List<Integer>) param.get("userIds");
        for(Integer userId : userIds) {
            Account account = new Account();
            account.setUserId(String.valueOf(userId));
            accountList.add(account);
        }
        accountMapper.batchUpdateUserPerm(accountList, String.valueOf(param.get("accId")));
    }

    public void updateAccountDeptPerm(Map param){
        List<Account> accountList = new ArrayList<>();
        Account account = new Account();
        account.setUserId(String.valueOf(param.get("deptId")));
        accountList.add(account);
        accountMapper.batchUpdateDeptPerm(accountList, String.valueOf(param.get("accId")));
    }


    public String queryAccFlagByUserId(String userId){
       return accountMapper.queryAccFlagByUserId(userId);
    }


}



